package com.gxuwz.attend.web.servlet.instructor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.entity.Student;
import com.gxuwz.attend.service.instructor.StudentService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/instructor/students")
public class StudentServlet extends HttpServlet {

    private StudentService studentService;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void init() throws ServletException {
        super.init();
        studentService = AppContext.getBean(StudentService.class);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String stuID = request.getParameter("stuID");
        String stuName = request.getParameter("stuName");
        int page = Integer.parseInt(request.getParameter("page"));
        int size = Integer.parseInt(request.getParameter("size"));
        int offset = (page - 1) * size;

        List<Student> students = studentService.getAllStudents(stuID, stuName, size, offset);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        String json = objectMapper.writeValueAsString(students);
        response.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Student student = objectMapper.readValue(request.getInputStream(), Student.class);
        studentService.addStudent(student);
        response.setStatus(HttpServletResponse.SC_CREATED); // 201 Created
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Student student = objectMapper.readValue(request.getInputStream(), Student.class);
        studentService.updateStudent(student);
        response.setStatus(HttpServletResponse.SC_OK); // 200 OK
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String stuID = request.getParameter("stuID");
        studentService.deleteStudent(stuID);
        response.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204 No Content
    }
}
